package com.wxw.BaseLibrary.http.soap;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import com.wxw.BaseLibrary.http.UploadImagePackage;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONStringer;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Set;

/**
 * Created by david on 14-3-5.
 */
public class SoapTool {
    public static final String TAG = "SoapTool";
    /**
     * Gets the lock for Handler to prevent the request result from confusing.
     */

    public static String Url = "";
//    /**
//     * 0为错误，1为正常
//     */
//    public static int Status = 0;
    public static int StatusCode = 0;
    public static String WEBSERVICE_SERVER_ADDRESS = "";
    public static String doPost(String url, HashMap<String, Object> params) {
        String strResp = "";
        Url = url;
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");//text/plain

        try {
            // 设置需调用WebService接口需要传入的两个参数mobileCode、userId
            if (params != null) {
                JSONStringer spa = new JSONStringer().object();
                Set<String> keys = params.keySet();
                for (String s : keys) {
                    spa.key(s).value(params.get(s));
                }
                spa.endObject();
                httpPost.setEntity(new StringEntity(spa.toString(), "utf-8"));
            }
            // 向WCF服务发送请求
            DefaultHttpClient httpClient = new DefaultHttpClient();
            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);
            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 300000);
            HttpResponse response = httpClient.execute(httpPost);

            StatusCode = response.getStatusLine().getStatusCode();
            // 判断是否成功
            if (StatusCode == HttpURLConnection.HTTP_OK){
                strResp = readFromInputStream(response.getEntity().getContent());
//                Status = 1;
            }else {
                strResp = response.getEntity().toString();
            }

            Log.d(TAG, "Saving : "
                    + response.getStatusLine().getStatusCode());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            strResp = e.getMessage();
            e.printStackTrace();
            Log.e(TAG, e.getMessage());
        }

        // Reload plate numbers

        return strResp;
    }

    /**
     * @param serviceName 服务的完整地址
     * @param methodName 数据对象
     * @param params Request的ContentType
     * @return 返回的json字符串
     */
    public static String doPost(String serviceName, String methodName, HashMap<String, Object> params) {
        String strResp = "";
        if (!WEBSERVICE_SERVER_ADDRESS.startsWith("http://")) {
            WEBSERVICE_SERVER_ADDRESS = "http://"+WEBSERVICE_SERVER_ADDRESS;
        }
        if (!WEBSERVICE_SERVER_ADDRESS.endsWith("/")) {
            WEBSERVICE_SERVER_ADDRESS += "/";
        }
        String url = WEBSERVICE_SERVER_ADDRESS+serviceName+"/"+methodName;
        return doPost(url, params);
//        HttpPost httpPost = new HttpPost(url);
//        httpPost.setHeader("Accept", "application/json");
//        httpPost.setHeader("Content-type", "application/json");//text/plain
//
//        try {
//            // 设置需调用WebService接口需要传入的两个参数mobileCode、userId
//            if (params != null) {
//                JSONStringer spa = new JSONStringer().object();
//                Set<String> keys = params.keySet();
//                for (String s : keys) {
//                    spa.key(s).value(params.get(s));
//                }
//                spa.endObject();
//                httpPost.setEntity(new StringEntity(spa.toString(), "utf-8"));
//            }
////            LinkedList<NameValuePair> rpc = new LinkedList<NameValuePair>();
////
////            for (String s : keys){
////                rpc.add(new BasicNameValuePair(s, params.get(s).toString()));
////            }
////            httpPost.setEntity(new UrlEncodedFormEntity(rpc,"utf-8"));
////            Gson gson = new Gson();
////            String s = gson.toJson(data);
////            StringEntity entity = new StringEntity(s);
////
////            request.setEntity(entity);
//
//            // 向WCF服务发送请求
//            DefaultHttpClient httpClient = new DefaultHttpClient();
//            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);
//            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 300000);
//            HttpResponse response = httpClient.execute(httpPost);
//            // 判断是否成功
//            if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK){
//                HttpEntity responseEntity = response.getEntity();
//                StringBuilder entityStringBuilder=new StringBuilder();
//
//                try {
//                    BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(responseEntity.getContent(), "UTF-8"), 8*1024);
//                    String line=null;
//                    while ((line=bufferedReader.readLine())!=null) {
//                        entityStringBuilder.append(line);
//                    }
//                    //利用从HttpEntity中得到的String生成JsonObject
//                    strResp = entityStringBuilder.toString();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
////                HttpEntity responseEntity = response.getEntity();
////                char[] buffer = new char[(int)responseEntity.getContentLength()];
////                InputStream stream = responseEntity.getContent();
////                InputStreamReader reader = new InputStreamReader(stream);
////                reader.read(buffer);
////                stream.close();
////                strResp = new String(buffer);
//            }
//
//            Log.d(TAG, "Saving : "
//                    + response.getStatusLine().getStatusCode());
//        } catch (Exception e) {
//            // TODO Auto-generated catch block
//            strResp = e.getMessage();
//            e.printStackTrace();
//            Log.e(TAG, e.getMessage());
//        }
//
//        // Reload plate numbers
//
//        return strResp;

    }

    public static String doGet(String url, String params) throws Exception {
        if (params != null && !"".equals(params)) {
            url += "?"+ params.replace("\n", "");
        }
        Url = url;
        String strRes = "";
        HttpGet request_get = new HttpGet(url);
        request_get.setHeader("Accept", "application/json");
        request_get.setHeader("Content-type", "application/json");

        BasicHttpParams basicHttpParams = new BasicHttpParams();
        ConnManagerParams.setTimeout(basicHttpParams, 10000);
        HttpConnectionParams.setConnectionTimeout(basicHttpParams, 20000);
        HttpConnectionParams.setSoTimeout(basicHttpParams, 20000);
        HttpConnectionParams.setSocketBufferSize(basicHttpParams,8*1024);
        HttpClientParams.setRedirecting(basicHttpParams, true);

        DefaultHttpClient httpClient = new DefaultHttpClient(basicHttpParams);
        try {
            HttpResponse response = httpClient.execute(request_get);
            StatusCode = response.getStatusLine().getStatusCode();
            if (StatusCode == HttpURLConnection.HTTP_OK) {
                strRes = readFromInputStream(response.getEntity().getContent());
//                Status = 1;
            } else {
                strRes = response.getEntity().toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            strRes = e.getMessage();
        }

        return strRes;
    }

    public static String doGet(String serviceName, String methodName, String params)
            throws Exception {
        if (!WEBSERVICE_SERVER_ADDRESS.startsWith("http://")) {
            WEBSERVICE_SERVER_ADDRESS = "http://"+WEBSERVICE_SERVER_ADDRESS;
        }
        if (!WEBSERVICE_SERVER_ADDRESS.endsWith("/")) {
            WEBSERVICE_SERVER_ADDRESS += "/";
        }
        String url = WEBSERVICE_SERVER_ADDRESS+serviceName+"/"+methodName;
        return doGet(url, params);
    }

    public static String toUploadFile(String url, String s, byte[] bytes) throws  FileNotFoundException {
        String strResp = "";
        long requestTime = System.currentTimeMillis();
        long responseTime = 0;
        Url = url;
        /**上传文件*/
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 1000*30);
        HttpConnectionParams.setSoTimeout(httpParameters, 1000*30);
        HttpConnectionParams.setTcpNoDelay(httpParameters, true);
        byte[] updata = UploadImagePackage.getPacket(s, bytes);    //参数与文件封装成单个数据包
        HttpClient httpClient = new DefaultHttpClient(httpParameters);
        HttpPost httpPost = new HttpPost(url);
        HttpResponse httpResponse;
        //单个文件流上传
        InputStream input = new ByteArrayInputStream( updata );
        InputStreamEntity reqEntity;
        reqEntity = new InputStreamEntity(input, -1);
        reqEntity.setContentType("binary/octet-stream");
        reqEntity.setChunked(true);
        httpPost.setEntity(reqEntity);
        try {
            httpResponse = httpClient.execute(httpPost);
            responseTime = System.currentTimeMillis();
            requestTime = (int) ((responseTime-requestTime)/1000);
            StatusCode = httpResponse.getStatusLine().getStatusCode();
            if (StatusCode ==200) {
                strResp = readFromInputStream(httpResponse.getEntity().getContent());
                Log.e(TAG, "request success");
                Log.e(TAG, "result : " + strResp);
            } else {
                Log.e(TAG, "request error");
//                sendMessage(UPLOAD_SERVER_ERROR_CODE,"上传失败：code=" + res);
                strResp = "request error";
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            strResp = e.getMessage();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            strResp = e.getMessage();
        }
        return strResp;
    }

    public static String toUploadFile(String serviceName, String methodName, String s, byte[] bytes) throws FileNotFoundException {
        if (!WEBSERVICE_SERVER_ADDRESS.startsWith("http://")) {
            WEBSERVICE_SERVER_ADDRESS = "http://"+WEBSERVICE_SERVER_ADDRESS;
        }
        if (!WEBSERVICE_SERVER_ADDRESS.endsWith("/")) {
            WEBSERVICE_SERVER_ADDRESS += "/";
        }
        String url = WEBSERVICE_SERVER_ADDRESS+serviceName+"/"+methodName;
        return toUploadFile(url, s, bytes);
    }
//
//    public static Handler getPosterHandler() {
//        synchronized (HANDLER_LOCK) {
//            if (sRequestHandler == null)
//                sRequestHandler = new Handler(Looper.getMainLooper());
//        }
//        return sRequestHandler;
//    }

    private static String readFromInputStream(InputStream stream) {
        StringBuilder entityStringBuilder=new StringBuilder();

        try {
            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(stream, "UTF-8"), 8*1024);
            String line=null;
            while ((line=bufferedReader.readLine())!=null) {
                entityStringBuilder.append(line);
            }
            //利用从HttpEntity中得到的String生成JsonObject
            return entityStringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
}
